﻿using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class Character : MonoBehaviour
{
	public UISprite sprite;
	public float size = 10;
	public float minJoinScale = 0.2f;
	public int sizeInt
	{
		get
		{
			return (int)size;
		}
	}
	void OnDrag(Vector2 offset)
	{
		if (!InputMngr.isMultiTouch)
		{
			transform.localPosition += new Vector3 (offset.x, offset.y);
			m_splitOther = null;

		}
		else
		{

			if (m_splitOther == null)
			{
				if ((InputMngr.position [0] - InputMngr.position [1]).magnitude > size)
				{
					m_splitOther = Split ();
				}
			}
			else
			{
				m_splitOther.transform.localPosition = InputMngr.position [0];
				transform.localPosition = InputMngr.position [1];
			}
		}
	}
	private Character m_splitOther = null;
	void Update()
	{
		sprite.SetDimensions ( sizeInt, sizeInt );
	}
	public float GetDistance(Character other)
	{
		return (transform.localPosition - other.transform.localPosition).magnitude;
	}
	public bool CheckJoin(Character other)
	{
		float distance = GetDistance (other);
		float minSize = Mathf.Min (other.size / 2, size / 2);
		float sum = size / 2 + other.size / 2 - minSize * minJoinScale;
		return sum > distance;
	}
	public float r
	{
		get
		{
			return size / 2;
		}
		set
		{
			size = (int)(value * 2);
		}
	}
	public void Join(Character owner)
	{
		//	position
		var dir = -(owner.transform.localPosition - transform.localPosition).normalized;
		var distance = GetDistance (owner);
		owner.transform.localPosition += dir * distance / 2;

		//	size
		owner.r = Mathf.Sqrt( r * r + owner.r * owner.r );



		Object.Destroy (gameObject);
	}
	[ContextMenu("Split")]
	public Character Split()
	{
		var offset = new Vector3 (halfAreaR * 2 * 1.1f, 0, 0);
		return Split (transform.localPosition, transform.localPosition + offset );
	}
	public float halfAreaR
	{
		get{
			return Mathf.Sqrt (r * r / 2);
		}
	}
	public Character Split(Vector3 p1, Vector3 p2)
	{
		var newObject = Object.Instantiate (gameObject) as GameObject;
		var other = newObject.GetComponent<Character> ();
		other.transform.parent = transform.parent;
		other.transform.localScale = Vector3.one;
		other.name = name;

		r = halfAreaR;
		other.r = r;

		other.transform.localPosition = p1;
		transform.localPosition = p2;

		return other;
	}

}
